<?php
namespace Home\Controller;
use Think\Controller;
use Think\Upload;
class IndexController extends Controller {
	public function index(){
       

		$this->display();
	}
    public function login(){
        $this->display();
    
    }


    /**
     * 检验登录信息
     */
    public function checkLogin(){
      
        /**检测用户名密码是否正确**/
        $username = I("username","","trim"); 	//接收用户名，并且使用trim函数去除首尾空格
        $password = I("password","","md5");	//接收密码，并且使用md5函数加密
        $return   = $this->checkPassword($username,$password);

        if(!$return){
            $res['status']  = 0;
            $res['message'] = '用户名或者密码错误!';
            $this->ajaxReturn($res);
        }else{
                
            session('user_id', $return["id"]);     //将user_id存入session
            session('user_username', $return["username"]); //将user_username存入session
            $res['status']  = 1;
            $res['message'] = '登录成功!';
            $this->ajaxReturn($res);
       }

    }

    /***
     * 检测用户名密码是否匹配
     * @param $username
     * @param $password
     * @return bool
     */
    public function checkPassword($username,$password){
        $map['username'] = $username;
        $user = M('user')->where($map)->find();
        if($user['password'] === $password){
            return $user;
        }else{
            return false;
        }
    }


    /**
     * 退出
     */
    public function logout(){
        unset($_SESSION['user_id']);
        unset($_SESSION['user_username']);
        $this->redirect("login");
    }
    /**
     * 注册
     */
    public function register(){
        $this->display();
    }
    /**
     * 注册成功
     */
    public function register_success(){
         if(IS_POST){
        
        $data['username'] = I('username'); 
        $data['password'] = I('password');
        $data['password2'] = I('password2');
            if (empty($data['username']))
        {
            $this->error('用户名不能为空');
        }
        if (empty($data['password']))
        {
            $this->error('密码不能为空');
        }
        if ( $data['password'] != $data['password2'])
        {
            $this->error('确认密码错误');
        }
        //查询表
        $User = M('user') ;
      //查找user表中是否有重名
      $datanum = $User->where(array('username' =>$data['username']))->find();
      //判断$datanum的值
      if ($datanum){
        $this->success('您已经注册过，请直接登录',U('login'));
      }else{
        $data['password'] = md5(I('password')); 
        $data['username']  = I('username');
        $data['addtime'] = time();
        $uid = $User->add($data);
        if($uid) 
          $this->success('注册成功',U('login')) ; 
        else 
          $this->error('注册失败') ; 
      }
     
    }
    }
/**
 * 发布微博
 * @return [type] [description]
 */
      public function ajax(){

    $user_id =  isset($_SESSION['user_id'])?$_SESSION['user_id']:"";
    if($user_id == '' ){
        echo -1;exit;
    }
    $post = M('post');
    //获取用户名
    $username = isset($_SESSION['user_username'])?$_SESSION['user_username']:"";
    //接收post提交的父id
    $pid      = isset($_POST['pid']) ? $_POST['pid'] : 0;
    //去除html标识
    $content  = isset($_POST['content']) ? strip_tags($_POST['content']) : "";
    //获取图片
    $pictures = isset($_POST['pictures']) ? $_POST['pictures'] : "";
    //微博类型
    $type     = isset($_POST['type']) ? $_POST['type'] : 0;
    //回复微博
    if($type == 1){
        $parent_user_id = $post->single('select user_id from mr_post where id = :id',
                                       array('id'=>$pid));//回复id
    }
    $parent_user_id = isset($parent_user_id) ? $parent_user_id : 0 ;

    $addtime  = time();
    $sql = array("user_id"=>$user_id,"username"=>$username,"content"=>$content, "pictures"=>$pictures , "addtime"=>$addtime,"pid"=>$pid,"type"=>$type,"parent_user_id"=>$parent_user_id);
        $result=$post->data($sql)->add();

        $post_id =$post->getLastInsID();
        // $post_id=$result;
        /** $type 0：发微博；1：评论微博；2：转发微博**/

    $user =M('user');
    switch ($type)
    {
        case 0:
           $sql = array("id"=>$user_id);
            $user->where($sql)->setInc('posts_num');
      break;
      case 1:
            $sql=array("pid"=>$pid);
            $post->where($sql)->setInc('comment_num');
            break;
        case 2:
             $sql = array("id"=>$user_id);
            $user->where($sql)->setInc('posts_num');
            $sq=array("pid"=>$pid);
           $post->where($sq)->setInc('forward_num');
      break;
        
    }
    if(strstr($content,"@")){  //判断微博内容中是否含有“@”字符
        /** 写入at表 **/
        $reg = "/@([^@\s]+)/";                  //正则匹配，得到@的用户
        $match = array();
        preg_match_all($reg,$content,$match);   //得到@用户数组
        $users_array = array_unique($match[1]); //去掉重复用户名
        if($users_array){
            $count = count($users_array);         //@的用户总数
            /**查看@用户是否存在，如果存在写入at表**/
            for($i = 0;$i < $count; $i++){
                //mr_user表中查找用户id是否存在
                 $map['username']=$users_array[$i];
               $user_id= $user->where($map)->getField('id');

                if($user_id){
                    $at =M('at');
                    $sql =array("user_id"=>$user_id,"post_id"=>$post_id);
                   $at->add($sql);
                   
            }
        }
    }


}
}
        public function upload(){
           $typeArr = array("jpg", "png", "gif", "jpeg"); //允许上传文件格式
$path = "Public/images/upload/post/"; //上传路径

if (isset($_POST)) {
    $name = $_FILES['file']['name'];
    $size = $_FILES['file']['size'];
    $name_tmp = $_FILES['file']['tmp_name'];
    if (empty($name)) {
        echo json_encode(array("error" => "您还未选择图片"));
        exit;
    }
    $type = strtolower(substr(strrchr($name, '.'), 1)); //获取文件类型

    if (!in_array($type, $typeArr)) {
        echo json_encode(array("error" => "请上传jpg,png或gif类型的图片！"));
        exit;
    }
    if ($size > (50000 * 1024)) { //上传大小
        echo json_encode(array("error" => "图片大小已超过50000KB！"));
        exit;
    }

    $pic_name = time() . rand(10000, 99999) . "." . $type; //图片名称
    $pic_url  = $path . $pic_name; //上传后图片路径+名称
    if (move_uploaded_file($name_tmp, $pic_url)) { //临时文件转移到目标文件夹
        echo json_encode(array("error" => "0", "pic" => $pic_url, "name" => $pic_name));
    } else {
        echo json_encode(array("error" => "上传有误，清检查服务器配置！"));
    }
}
    }


}